package com.java.module.chat.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import com.java.common.service.ApiTokenService;
import com.java.common.utils.spring.SpringUtils;
import com.java.module.chat.domain.ChatGroup;
import com.java.module.chat.domain.GroupUser;
import com.java.module.chat.mapper.ChatMessageMapper;
import com.java.module.chat.service.IChatGroupService;

import com.java.module.chat.service.IGroupUserService;
import com.java.module.chat.domain.ChatMessage;
import com.java.module.chat.domain.Session;
import com.java.module.chat.domain.dto.SessionDTO;
import com.java.module.chat.domain.vo.ChatMessageVO;
import com.java.module.chat.util.MsgTypeEnum;
import com.java.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.java.common.lang.domain.entity.User;
import com.java.common.utils.DateUtils;
import com.java.common.utils.WebKit;
import com.java.module.chat.mapper.SessionMapper;
import com.java.module.chat.service.ISessionService;
import com.java.module.system.service.ISysUserService;
import com.java.module.user.service.IUserService;
import com.vdurmont.emoji.EmojiParser;

/**
 * 聊天：会话列Service业务层处理
 * 
 * @author Administrator
 * @date 2021-05-13
 */
@Service
public class SessionServiceImpl implements ISessionService {

    @Autowired
    private SessionMapper sessionMapper;

    @Autowired
    private ChatMessageMapper chatMessageMapper;

    @Autowired
    private IUserService userSrv;

    @Autowired
    private ISysUserService adminSrv;

    @Autowired
    private IChatGroupService groupService;
    @Autowired
    private IGroupUserService groupUserService;

    @Autowired
    private IUserService userService;

    /**
     * 查询聊天：会话列
     * 
     * @param sessionId 聊天：会话列ID
     * @return 聊天：会话列
     */
    @Override
    public Session selectSessionById(Long sessionId) {
        return sessionMapper.selectSessionById(sessionId);
    }

    /**
     * 查询聊天：会话列列表
     * 
     * @param session 聊天：会话列
     * @return 聊天：会话列
     */
    @Override
    public List<Session> selectSessionList(SessionDTO session) {
        List<Session> list = sessionMapper.selectSessionListAdmin(session);
        for (Session record : list) {
            Long uid = record.getOtherSideUid();
            if(record.getSessionType()==2) {
                uid=record.getUid();
            }
            if (uid != null) {
                User user = userSrv.selectUserById(uid);
                record.setNickname(user.getNickname());
                record.setAvatar(user.getAvatar());
            }
            if (MsgTypeEnum.TEXT.getMsgType().equals(record.getMsgType())) {
                record.setMsgContent(EmojiParser.parseToUnicode(record.getMsgContent()));
            }
            if (MsgTypeEnum.IMAGE.getMsgType().equals(record.getMsgType())) {
                record.setMsgContent(WebKit.getHttpFullPath(record.getMsgContent()));
            }
        }
        return list;
    }

    /**
     * 查询单个聊天：会话列
     * 
     * @param session 聊天：会话列
     * @return 聊天：会话列
     */
    @Override
    public Session selectSession(Session session) {
        return sessionMapper.selectSession(session);
    }

    /**
     * 查询客服未读消息数量
     * 
     * @param uid
     * @return 结果
     */
    @Override
    public int getUnreadMsgCount(Long uid) {
        return sessionMapper.getUnreadMsgCount(uid);
    }

    /**
     * 查询客服未读消息数量
     * 
     * @param uid
     * @return 结果
     */
    @Override
    public Session getUnreadMsg(Long uid) {
        return sessionMapper.getUnreadMsg(uid);
    }

    /**
     * 新增聊天：会话列
     * 
     * @param session 聊天：会话列
     * @return 结果
     */
    @Override
    public int insertSession(Session session) {
        session.setCreateTime(DateUtils.getNowDate());
        return sessionMapper.insertSession(session);
    }

    /**
     * 修改聊天：会话列
     * 
     * @param session 聊天：会话列
     * @return 结果
     */
    @Override
    public int updateSession(Session session) {
        session.setUpdateTime(DateUtils.getNowDate());
        Session s = sessionMapper.selectSessionById(session.getSessionId());
        if (s != null && s.getAdminDelFlag() == 1) {
            session.setAdminDelFlag(0);
        }
        return sessionMapper.updateSession(session);
    }

    /**
     * 批量删除聊天：会话列
     * 
     * @param sessionIds 需要删除的聊天：会话列ID
     * @return 结果
     */
    @Override
    public int deleteSessionByIds(Long[] sessionIds) {
        return sessionMapper.deleteSessionByIds(sessionIds);
    }

    /**
     * 删除聊天：会话列信息
     * 
     * @param sessionId 聊天：会话列ID
     * @return 结果
     */
    @Override
    public int deleteSessionById(Long sessionId) {
        return sessionMapper.deleteSessionById(sessionId);
    }

    /**
     * 会话列表
     * 
     * @param uid
     * @return
     */
    @Override
    public List<Session> getSessionList(Long uid,ChatMessage body) {
        SessionDTO sessionDTO = new SessionDTO();
        sessionDTO.setUid(uid);
        sessionDTO.setUsername(body.getKey());
        User user = SpringUtils.getBean(IUserService.class).selectUserById(uid);
        //userService.selectUserById(uid)
        if(user !=null){
            sessionDTO.setIsReceive(user.getIsReceive());
        }
        if(StringUtils.isNotNull(body.getType())){
            sessionDTO.setType(body.getType());
        }
        List<Session> list = sessionMapper.selectSessionList(sessionDTO);
        list.stream().forEach(s -> resetSession(s));
        return list;
    }

    /**
     * 查询后台用户信息
     *
     * @param loginUserId
     */
    @Override
    public Session getAdminSession(Long loginUserId) {
        Session session = new Session();
        session.setUid(loginUserId);
        session.setOtherSideUid(0L);
        Session adminSession = sessionMapper.getAdminSession(session);
        if(adminSession == null){
            adminSession = new Session();
        }else {
            adminSession.setMsgContent(EmojiParser.parseToUnicode(adminSession.getMsgContent()));
        }
        return adminSession;
    }

    /**
     * 获取用户信息
     * 
     * @param uid id
     * @param type 类型 1单聊 2群聊
     * @return
     */
    @Override
    public Map<String, String> getUserInfo(Long uid,Integer type) {
        Map<String, String> resule = new HashMap<>();
        if(type == 1){
            User user = userSrv.selectUserById(uid);
            if(user != null){
                resetUserInfo(user);
                resule.put("name",getUserNickname(user));
                resule.put("avatar",WebKit.getHttpFullPath(user.getAvatar()));
            }
        }else if(type == 2){
            ChatGroup chatGroup = groupService.selectChatGroupById(uid);
            resule.put("name",chatGroup.getName());
            resule.put("avatar", WebKit.getHttpFullPath(chatGroup.getAvatar()));

            //查询群聊人数
            GroupUser groupUser=new GroupUser();
            groupUser.setGid(uid);
            List<GroupUser> groupUserList = groupUserService.selectGroupUserList(groupUser);
            resule.put("number", String.valueOf(groupUserList.size()));
            //查询自己是否未群主


        }
        return resule;
    }

    @Override
    public Map<String, String> getGroupInfo(Long gid, Integer type, Long loginUid) {
        Map<String, String> resule = new HashMap<>();
        if(type == 1){
            User user = userSrv.selectUserById(gid);
            User user2 = new User();
            user.setUid(loginUid);
            user.setCid(gid);
            int  isGuanzhu = userSrv.selectCount(user2);
            if(user != null){
                resetUserInfo(user);
                resule.put("name",getUserNickname(user));
                resule.put("userType",String.valueOf(user.getUserType()));
                resule.put("avatar",WebKit.getHttpFullPath(user.getAvatar()));
                resule.put("isGuanzhu",String.valueOf(isGuanzhu));
                resule.put("checkStatus",user.getCheckStatus());
                resule.put("companyAuthStatus",String.valueOf(user.getCompanyAuthStatus()));
                resule.put("bpAuthStatus",String.valueOf(user.getBpAuthStatus()));
                resule.put("schoolAuthStatus",String.valueOf(user.getSchoolAuthStatus()));
                resule.put("investAuthStatus",String.valueOf(user.getInvestAuthStatus()));

                //判断是否是好友

            }
        }else if(type == 2){
            ChatGroup chatGroup = groupService.selectChatGroupById(gid);
            if(com.java.common.utils.StringUtils.isNull(chatGroup)){
                return resule;
            }
            resule.put("name",chatGroup.getName());
            resule.put("avatar", WebKit.getHttpFullPath(chatGroup.getAvatar()));
            //查询群聊人数
            GroupUser groupUser=new GroupUser();
            groupUser.setGid(gid);
            List<GroupUser> groupUserList = groupUserService.selectGroupUserList(groupUser);
            resule.put("number", String.valueOf(groupUserList.size()));
            //查询自己是否未群主
            if(chatGroup.getUid().equals(loginUid)){
                resule.put("admin", "Y");
            }
        }
        return resule;
    }

    /**
     * 获取用户信息
     */
    @Override
    public void getUserInfo(ChatMessageVO messageVO) {
        Long uid = messageVO.getMsgFromUid();
        User user = userSrv.selectUserById(uid);
        if (user == null) {
            return;
        }
        messageVO.setNickname(getUserNickname(user));
        messageVO.setAvatar(user.getAvatar());
    }

    /**
     * 获取用户“昵称”
     *
     * @param user
     * @return
     */
    @Override
    public String getUserNickname(User user) {
        if (user == null) {
            return "";
        }
        String nickname = user.getNickname();
        String realname = user.getRealname();
        String username = user.getUsername();

        if (StringUtils.isNotBlank(realname)) {
            return realname;
        }
        if (StringUtils.isNotBlank(nickname)) {
            return nickname;
        }
        if (StringUtils.isNotBlank(username)) {
            return StringUtils.abbreviateMiddle(username, "****", 10);
        }
        return "";
    }

    /**
     * 获取用户“昵称”
     *
     * @param uid
     * @return
     */
    public String getUserNickname(Long uid) {
        return this.getUserNickname(userSrv.selectUserById(uid));
    }

    /**
     * 保存会话
     * 
     * @param uid
     * @param toUid
     * @return
     */
    public boolean saveSession(Long uid, Long toUid, Integer chatType, Integer userType, ChatMessage message,
            Integer unreadMsgCount,Integer sessionType, Integer type) {
        boolean isSave = false;
        Session selectSession = new Session();
        selectSession.setUid(uid);
        selectSession.setOtherSideUid(toUid);
        //selectSession.setUserType(userType);
        selectSession.setChatType(chatType);
        selectSession.setSessionType(sessionType);
        Session session = selectSession(selectSession);
        if (session == null) {
            isSave = true;
            session = new Session();
        } else {
            session.setSessionId(session.getSessionId());
        }
        if (message != null) {
            session.setMsgType(message.getMsgType());
            session.setMsgContent(message.getMsgContent());
            session.setMsgExtra(message.getMsgExtra());
        }
        session.setMsgIntime(DateUtils.getNowDate());
        session.setSessionType(sessionType);
        session.setUserUnreadCount(unreadMsgCount);
        session.setUid(uid);
        session.setChatType(chatType);
        session.setUserType(userType);
        session.setOtherSideUid(toUid);
        session.setType(type);
        int num = 0;
        if (isSave) {
            num = insertSession(session);
        } else {
            num = updateSession(session);
        }
        return num > 0;
    }

    /**
     * 刷新消息
     * 
     * @param msgFromUid
     * @param msgToUid
     * @param chatType
     * @param userType
     * @param message
     * @param unreadMsgCount
     */
    @Override
    public void refreshSession(Long msgFromUid, Long msgToUid, Integer chatType, Integer FromType, Integer toUserType, ChatMessage message,
            Integer unreadMsgCount,Integer sessionType) {
        if(sessionType == 1){
            int userTypeType = 0;
            if(toUserType == 0){

            }

            this.saveSession(msgFromUid, msgToUid, chatType, toUserType, message, 0,sessionType, toUserType);
            if (message != null) {
                ChatMessage.MsgExtra msgExtra = message.getMsgExtra();
                if (msgExtra != null) {
                    String fromEcardNumber = msgExtra.getFromEcardNumber();
                    String toEcardNumber = msgExtra.getToEcardNumber();
                    msgExtra.setToEcardNumber(fromEcardNumber);
                    msgExtra.setFromEcardNumber(toEcardNumber);
                }
            }

            this.saveSession(msgToUid, msgFromUid, chatType, FromType, message, unreadMsgCount,sessionType, FromType);
        }else{
            this.saveSession(msgFromUid, msgToUid, chatType, toUserType, message, 0,sessionType,FromType);
            SessionDTO session = new SessionDTO();
            session.setSessionType(sessionType);
            session.setOtherSideUid(msgToUid);
            for (Session session1 : sessionMapper.selectSessionList(session)) {
                if(!Objects.equals(msgFromUid, session1.getUid())){
                    Integer count = session1.getUserUnreadCount() + 1;
                    this.saveSession(session1.getUid(), msgToUid, chatType, toUserType, message, count,sessionType,FromType);
                }
            }

        }
    }

    @Override
    public int updateSessionMsgRead(Session session) {
        return sessionMapper.updateSessionMsgRead(session);
    }

    private void resetSession(Session session) {
        if (session == null) {
            return;
        }

        // TODO 群聊暂未处理
        Long otherSideUid = session.getOtherSideUid();
        Map<String, String> userInfo = getUserInfo(otherSideUid, session.getSessionType());

        if (userInfo != null) {
            session.setNickname(userInfo.get("name"));
            session.setAvatar(userInfo.get("avatar"));
        }

        Integer msgType = session.getMsgType();
        String msgContent = StringUtils.trim(session.getMsgContent());
        if (MsgTypeEnum.TEXT.getMsgType().equals(msgType)) {
            msgContent = EmojiParser.parseToUnicode(msgContent);
        } else if (MsgTypeEnum.IMAGE.getMsgType().equals(msgType)) {
            msgContent = WebKit.getHttpFullPath(msgContent);
        }
        session.setMsgContent(msgContent);
        session.setCreateTime(null);
        session.setUpdateTime(null);
        session.setDelFlag(null);
        session.setAdminDelFlag(null);
        session.setUserType(null);
    }

    /**
     * 设置昵称和头像
     *
     * @param
     * @param users
     */
    private void resetUserInfo(User... users) {
        for (User user : users) {
            if (user == null) {
                continue;
            }
            user.setNickname(getUserNickname(user));
            user.setAvatar(WebKit.getHttpFullPath(user.getAvatar()));
        }
    }

    @Override
    public Integer getUserUnreadCount(Long uid) {
        return sessionMapper.getUserUnreadCount(uid);
    }

    /**
     * 增加会话记录
     * @param otherSideUid 活动id
     * @param sessionType 类型
     * @param uid 登录用户id
     * @return
     */
    @Override
    public boolean addSession(Long otherSideUid, Integer sessionType,Long uid,Integer type) {
        return this.saveSession(uid, otherSideUid, 0, 0, new ChatMessage(), 0, sessionType,type);
    }
}